<template>
  <v-page
    background="#f5f6fa"
    header-background="white"
    footer-background="white"
    padding-top="24rpx"
  >
    <template #header>
      <v-navbar title="投诉反馈" />
    </template>
    <template #default>
      <view class="complaint-block">
        <view
          v-if="!formData.product"
          class="complaint-item"
          @click="selectProduct"
        >
          <view class="label required">
            选择问题商品
          </view>
          <view class="content">
            <wd-icon name="arrow-right" size="24rpx" color="#999999" />
          </view>
        </view>
        <view
          v-else-if="order"
          class="complaint-product-container"
          @click="selectProduct"
        >
          <view class="complaint-product">
            <view class="header">
              <v-icon size="36rpx" src="@/static/icons/cart-merchant.svg" />
              <view class="merchant-name">
                <view class="name-text">
                  {{ order.merchant_name }}
                </view>
              </view>
            </view>
            <complaint-product :product="formData.product" />
            <view class="summary">
              <view class="summary-label">
                实付
              </view>
              <v-price :price="productPrice" size="32rpx" color="#333333" />
            </view>
          </view>
          <wd-icon name="arrow-right" size="24rpx" color="#999999" />
        </view>
      </view>
      <view class="complaint-block" @click="selectReason">
        <view class="complaint-item">
          <view class="label required">
            选择投诉原因
          </view>
          <view class="content">
            <view v-if="formData.reason">
              {{ reasons[formData.reason] }}
            </view>
            <wd-icon name="arrow-right" size="24rpx" color="#999999" />
          </view>
        </view>
      </view>
      <view class="complaint-block">
        <view class="inline-label required">
          问题描述
        </view>
        <v-textarea
          v-model="formData.content"
          :custom-style="{ height: '200rpx' }"
          :maxlength="500"
          placeholder="请输入问题情况，详细的描述有助于更好地解决问题"
        />
        <v-uploader
          v-model="formData.image"
          v-model:loading="uploading"
          :pre-list="formData.image"
          upload-url="/storefront/v1/file/upload/image"
          upload-name="file"
          :extra-data="{ type: 'ORDER_COMPLAINT_IMAGE' }"
          :max-length="6"
        />
      </view>
      <view class="complaint-block">
        <view class="complaint-item">
          <view class="label">
            联系电话
          </view>
          <view class="content">
            <v-input
              v-model="formData.mobile"
              type="tel"
              placeholder="请输入联系电话"
              :custom-style="{ width: '100%', textAlign: 'right' }"
              :maxlength="11"
            />
          </view>
        </view>
      </view>
    </template>
    <template #footer>
      <view class="submit-button-container">
        <v-button type="primary" @click="submitHandle">
          确认提交
        </v-button>
      </view>
    </template>
    <template #popup>
      <complaint-reason-popup
        v-model:show="isShowReason"
        v-model:reason="formData.reason"
        :type="formData.type"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import ComplaintProduct from './modules/complaint-product.vue';
import ComplaintReasonPopup from './modules/complaint-reason-popup.vue';

const order = ref<OrderVO>();
const reasons = {
  UNSHIPPED: '超时未发货',
  LESS_SHIPPED: '少发',
  WRONG_SHIPPED: '错发',
  SHAM_SHIPPED: '虚假发货',
  DISCREPANCY_DESCRIPTION: '描述不符',
  DAMAGED: '商品破损',
  QUALITY_PROBLEM: '质量问题',
  CUSTOMER_SERVICE_NOT_REPLY: '客服不回复',
  CUSTOMER_SERVICE_NOT_PROCESS: '客服不处理',
  ABNORMAL_ATTITUDE: '态度异常',
  MINI_PROGRAM_EXPERIENCE: '小程序体验',
  ALIPAY_REPORT: '支付宝举报'
};

const formData = ref<{
  /** 联系手机 */
  mobile?: string;
  /** 投诉类型 */
  type: 'DELIVERY' | 'PRODUCT' | 'CUSTOMER_SERVICE' | 'OTHER';
  /** 投诉原因 */
  reason: keyof typeof reasons | undefined;
  /** 客户备注 */
  content: string;
  /** 图片 */
  image?: string[];
  /** 投诉商品 */
  product?: OrderDetailVO;
}>({
  type: 'DELIVERY',
  reason: undefined,
  content: '',
  image: []
});
const productPrice = computed(() => {
  if (!formData.value.product) return 0;
  const product = formData.value.product;
  const val =
    product.sell_price * product.quantity - (product.discount_price ?? 0);
  return Math.max(val, 0);
});
const selectProduct = () => {
  const pageStore = $store.page();
  pageStore.setParameters({
    order: order.value,
    product: formData.value.product
  });
  uni.navigateTo({
    url: '/pages/complaint/complaint-product-select'
  });
};
onLoad(() => {
  uni.$on('complaint-product-select', (product: OrderDetailVO) => {
    formData.value.product = product;
  });
});
onUnload(() => {
  uni.$off('complaint-product-select');
});

const isShowReason = ref(false);
const selectReason = () => {
  isShowReason.value = true;
};

onLoad((query) => {
  if (query) {
    formData.value.type = query.type as
      | 'DELIVERY'
      | 'PRODUCT'
      | 'CUSTOMER_SERVICE'
      | 'OTHER';
  }
  const pageStore = $store.page();
  const parameters = pageStore.parameters as {
    order: OrderVO;
  };
  order.value = parameters.order;
});

const uploading = ref(false);
const validate = async () => {
  if (uploading.value) {
    uni.showToast({ title: '图片上传中，请稍后', icon: 'none' });
    return false;
  }
  if (!formData.value.product) {
    uni.showToast({ title: '请选择问题商品', icon: 'none' });
    return false;
  }
  if (!formData.value.reason) {
    uni.showToast({ title: '请选择投诉原因', icon: 'none' });
    return false;
  }
  if (!formData.value.content) {
    uni.showToast({ title: '请输入问题描述', icon: 'none' });
    return false;
  }
  if (!formData.value.image?.length) {
    uni.showToast({ title: '请上传图片', icon: 'none' });
    return false;
  }
  const mobile = formData.value.mobile;
  if (mobile && !/^1([35689]\d|7[3-8]|4[5-7])\d{8}$/.test(mobile)) {
    uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
    return false;
  }
  return true;
};

const submitHandle = async () => {
  const valid = await validate();
  if (!valid) return;
  uni.showLoading({ mask: true });
  const response = await $api.postOrderComplaintSubmit({
    order_detail_id: formData.value.product?.id ?? '',
    reason: formData.value.reason as keyof typeof reasons,
    problem_type: formData.value.type,
    content: formData.value.content,
    mobile: formData.value.mobile ?? order.value?.recipient_info?.mobile ?? '',
    image: formData.value.image ?? []
  });
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '提交成功', icon: 'none' });
      uni.redirectTo({
        url: `/pages/complaint/complaint-details?id=${response.data}`
      });
      break;
  }
};
</script>

<style lang="scss" scoped>
.complaint-block {
  margin: 0 24rpx 20rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 16rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 20rpx;
  .inline-label {
    font-size: 30rpx;
    line-height: 40rpx;
    font-weight: bold;
    &.required::before {
      content: '*';
      color: red;
      margin-right: 4rpx;
    }
  }
  .complaint-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24rpx;
    min-height: 60rpx;
    .label {
      flex-shrink: 0;
      &.required::before {
        content: '*';
        color: red;
        margin-right: 4rpx;
      }
    }
    .sub-label {
      color: #999999;
      font-weight: 300;
      flex: 1;
      min-width: 0;
    }
    .content {
      flex: 1;
      min-width: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12rpx;
    }
  }

  .complaint-product-container {
    display: flex;
    align-items: center;
    gap: 16rpx;
    .complaint-product {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      gap: 28rpx;
      .header {
        height: 40rpx;
        display: flex;
        align-items: center;
        gap: 20rpx;
        .merchant-name {
          flex: 1;
          min-width: 0;
          display: flex;
          align-items: center;
          .name-text {
            font-size: 28rpx;
            font-weight: bold;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            word-break: break-all;
          }
        }
      }
      .summary {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        gap: 8rpx;
        .summary-label {
          font-size: 28rpx;
        }
      }
    }
  }
}
.submit-button-container {
  margin: 0 24rpx 24rpx;
  padding: 10rpx 0;
}
</style>
